package com.augurit.wf.bi.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.base.action.ExtBaseAction;
import com.augurit.common.base.action.ExtCrudActionSupport;
import com.augurit.common.base.extmodel.BasicCombo;
import com.augurit.common.base.extmodel.inner.ExtMetaColumnNode;
import com.augurit.common.base.extmodel.inner.ExtMetaTableNode;
import com.augurit.common.base.form.Attachment;
import com.augurit.common.base.form.ResultForm;
import com.augurit.common.constant.SystemConstant;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.sysmeta.convert.SysMetaColumnConvertor;
import com.augurit.common.sysmeta.convert.SysMetaTableConvertor;
import com.augurit.common.sysmeta.service.ISysMetaColumnService;
import com.augurit.common.sysmeta.service.ISysMetaTableService;
import com.augurit.common.sysmeta.web.form.SysMetaColumnForm;
import com.augurit.common.sysmeta.web.form.SysMetaTableForm;
import com.augurit.common.util.ActionUtils;
import com.augurit.common.util.ExtUtils;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.service.IWfTemplateAttachmentRefService;
import com.augurit.wf.bi.web.form.WfTemplateAttachmentRefForm;

@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "wf-template-print-ref.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/wf/bi/bus-template/edit-print-template.jsp"),
	@Result(name = WfTemplatePrintRefAction.EDIT_FORM_PRINT_TEMPLATE, location = "/wf/bi/bus-template/edit-form-and-print-template.jsp")
})
public class WfTemplatePrintRefAction extends ExtCrudActionSupport<WfTemplateAttachmentRefForm> {
	
	private static final String EDIT_FORM_PRINT_TEMPLATE = "edit-form-print-template";	//对应
	
	@Autowired
	private IWfBusTemplateService wfBusTemplateService;
	
	@Autowired
	private IWfTemplateAttachmentRefService wfTemplatePrintRefService;
	
	@Autowired
	private ISysMetaColumnService sysMetaColumnService;
	@Autowired
    private ISysCodeService syscodeService;
	
	private Page<WfTemplateAttachmentRefForm> page = new Page<WfTemplateAttachmentRefForm>(15);
	private WfTemplateAttachmentRefForm form;
	
	private Long id;
	private Long[] ids;
	
	private Attachment document; 	//保存ntko文档文件对象
	
	/**
	 * 显示业务流程对应的打印模板列表
	 */
	@Override
	public String list() throws Exception {
		ExtUtils.initPageFromExtGridParam(ExtBaseAction.getRequest(), page);
		wfTemplatePrintRefService.search(page, form);
		ExtBaseAction.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 显示模板下的所以红头文件
	 * @return
	 * @throws Exception
	 */
	public String listRedHeadFiles() throws Exception {
		
		List<WfTemplateAttachmentRefForm> list = wfTemplatePrintRefService.listAllRedHeadFiles(form.getTemplateCode());
		
		if(list != null && list.size() > 0){
			List<BasicCombo> combos = new ArrayList<BasicCombo>();
			for(int i = 0; i < list.size(); i++){
				WfTemplateAttachmentRefForm printForm = list.get(i);
				
				BasicCombo combo = new BasicCombo();
				combo.setLabel(printForm.getFileName());
				combo.setValue(printForm.getFilePath()+ "/" + printForm.getFileName());
				combos.add(combo);
			}
			ExtBaseAction.extRenderListJson(combos, true);
		}
		return null;
	}
	
	/**
	 * 保存上传的打印模板打印模板及对应的表单
	 */
	@Override
	public String save() throws Exception {
		List<Attachment> attachments = this.getAttachmentList();
		
		if(attachments == null || attachments.size() != 1){
			throw new Exception("上传打印模板失败！");
		}
		else {
			//上传附件
			Attachment attachment = attachments.get(0);
			this.uploadFile(form.getFilePath(), attachment.getFileFileName(), attachment, false, true, true);
			
			//保存form
			form.setFileName(attachments.get(0).getFileFileName());
			wfTemplatePrintRefService.save(form);
			renderHtml("{'success':true}");
		}
		return null;
	}
	
	/**
	 * 删除打印模板
	 */
	@Override
	public String delete() throws Exception {
		if(ids != null && ids.length > 0){
			for(Long id:ids){
				wfTemplatePrintRefService.deleteCascade(id);
			}
		}
		ExtBaseAction.extRenderSuccess();
		return null;
	}

	/**
	 * 编辑打印模板及对应的表单
	 * @return
	 * @throws Exception
	 */
	public String editFormAndPrintTemplate() throws Exception {
		 // 秘密等级
        List<SysCodeForm> fileTypeList = syscodeService.getItems("WF_PRINT_TPL_TYPE");
        if(form != null && form.getFileType() != null){
        	for(SysCodeForm code : fileTypeList){
        		if(code.getItemCode().equals(form.getFileType()))
        			form.setFileTypeChineseName(code.getItemName());
        	}
        }
        super.getRequest().setAttribute("fileTypeList", fileTypeList);
        return EDIT_FORM_PRINT_TEMPLATE;
	}
	
	/**
	 * 保存打印模板及对应的表单
	 * @return
	 * @throws Exception
	 */
	public String saveFormAndPrintTemplate() throws Exception {
		ResultForm result = new ResultForm(true);
		boolean success = this.uploadFile(form.getFilePath(), form.getFileName(), document, false, true, true);
		if(success){
			wfTemplatePrintRefService.save(form);
			result.setErrMsg("已成功保存附件！");
		}
		else{
			ActionUtils.setErrMsgOfResult(result, "上传附件内容失败！");
		}
		this.renderJson(result, SystemConstant.ENCODING_GBK);
		return null;
	}
	
	/**
	 * 读取打印模板文件
	 * @return
	 * @throws Exception
	 */
	public String readPrintTemplateFile() throws Exception{
		InputStream in = null;
    	ServletOutputStream out = null;
    	
    	String filePathName = wfTemplatePrintRefService.getPrintTemplateRelativePath(form.getTemplateId(), form.getFileCode()) ;
        
    	if(filePathName == null){
        	filePathName = "/wf/bi/bus-template/blank-template/blank.doc";
        }
    	try {
        	File file = null;
        	
        	filePathName = ExtBaseAction.getApplication().getRealPath("/") +  filePathName;
            file = new File(filePathName);
            
        	//重置response
            ExtBaseAction.getResponse().reset();
            ExtBaseAction.getResponse().setContentType("application/octet-stream");
            
            ExtBaseAction.getResponse().setHeader("Content-Disposition","attachment; filename=" + filePathName);

            in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
            out = ExtBaseAction.getResponse().getOutputStream();
            byte[] buffer = new byte[BUFFER_SIZE];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
            	out.write(buffer, 0, n);
            }
            
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
			try {
				if(in != null) {
					in.close();
				}
				if(out != null) {
					out.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
        
		return null;
	}
	
	/**
	 * 获取业务表字段列表
	 * @throws Exception
	 */
	public String getBusTableFields()throws Exception {
		//获取业务表
		List<SysMetaTableForm> tables = wfBusTemplateService.getRelateEntities(form.getTemplateId());
		List<ExtMetaTableNode> nodes = null;
		
		if(tables != null && tables.size() > 0){
			
			nodes = new ArrayList<ExtMetaTableNode>();
			//对于每一个表
			for(SysMetaTableForm metaTableForm:tables){
				
				ExtMetaTableNode node = SysMetaTableConvertor.convertToExtNode(metaTableForm);
				//获取表中的字段
				List<SysMetaColumnForm> columns = sysMetaColumnService.getColumnsByTableId(metaTableForm.getId());
				
				List<ExtMetaColumnNode> children = SysMetaColumnConvertor.convertToExtNodeList(columns);
				node.setChildren(children);
				if(children == null)
					node.setLeaf(true);
				nodes.add(node);
			}
		}
		
		extRenderListJson(nodes, false);
		return null;
	}
	
	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub
		if(id != null){
			form = wfTemplatePrintRefService.get(id);
		}
		else
			form = new WfTemplateAttachmentRefForm();
	}

	public WfTemplateAttachmentRefForm getModel() {
		// TODO Auto-generated method stub
		return form;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getIds() {
		return ids;
	}

	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	public Attachment getDocument() {
		return document;
	}

	public void setDocument(Attachment document) {
		this.document = document;
	}

}
